package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myapplication.socket.LocalSocketStart;
import com.example.myapplication.socket.ServerSocketStart;
import com.example.myapplication.socket.TcpClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LocalReceiveActivity extends AppCompatActivity {

    private Button localReceiveStartBtn;
    Handler handler;
    private LocalSocketStart localSocketStart;
    private ServerSocket serverSocket;
    private Socket socket;
    private Socket socket1;
    private OutputStream outputStream;
    private TextView localDeviceDataTv;
    private ServerSocketStart serverSocketStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_receive);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x126) {
                    String result = (String) msg.obj;
                    if (socket1 != null){
                        try {
                            outputStream = socket1.getOutputStream();
                            if (result == "") {
                                outputStream.write(result.getBytes());

                            } else {
                                outputStream.write(result.getBytes());
                                outputStream.flush();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(msg.what == 0x128){
                    String result = (String) msg.obj;
                    localDeviceDataTv.setText(result);
                }
            }
        };

        initView();
        initEvent();

    }

    public void initView() {
        localDeviceDataTv = findViewById(R.id.local_receive_data_tv);

        localReceiveStartBtn = findViewById(R.id.local_receive_start_btn);
    }

    public void initData() {
        serverSocketStart = new ServerSocketStart(handler, 60002);
        serverSocketStart.start();
        localSocketStart = new LocalSocketStart(8081);
        localSocketStart.start();
        TcpClient tcpClient = new TcpClient("127.0.0.1", 8081,handler);
        tcpClient.start();


    }

    public void initEvent() {
        localReceiveStartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

    }


    public class LocalSocketStart extends Thread {
        private final String TAG = "ServerThread";
        private ServerSocket serverSocket;
        private boolean isServerRuning = false; //服务器是否在运行
        public Map<String, com.example.myapplication.socket.LocalSocketStart.SocketThread> socketThreadMap = new HashMap<>(); //客户端列表  ip:端口，客户端
        private int port = 0;
        private Handler handler = null;
        private String sendData = null;

        public LocalSocketStart(int port) {
            this.handler = handler;
            this.port = port;
        }


        public void start() {
            try {
                serverSocket = new ServerSocket(port);
                isServerRuning = true;
                super.start();
                Log.e(TAG, "本地服务器运行成功");
            } catch (IOException e) {
                e.printStackTrace();
                isServerRuning = false;
                Log.e(TAG, "服务器运行失败");
            }
        }

        @Override
        public void interrupt() {
            isServerRuning = false;
            if (socketThreadMap != null) {
                Log.e(TAG, "连接本地客户端个数：" + socketThreadMap.size());
                Iterator<String> iterator = socketThreadMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    socketThreadMap.get(key).interrupt();
                }
                socketThreadMap.clear();
                socketThreadMap = null;
            }
            Log.e(TAG, "连接本地客户端资源释放完毕");
            //关闭服务器
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                    serverSocket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.e(TAG, "关闭本地服务器完毕");
            super.interrupt();
        }

        //获取服务器是否在运行
        public boolean isServerRuning() {
            return isServerRuning;
        }

        @Override
        public void run() {
            super.run();
            while (isServerRuning()) {
                try {
                    //等待客户端连接
                    socket1 = serverSocket.accept();
                    Log.e(TAG, "连接本地客户端连接上：" + socket1.toString());
                    if (socket1 != null) {
                        Log.d(TAG, "run: " + "来了老弟");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}